<template>
  <view :style="[styles]" class="content">
    <text class="title" :style="{color:attribute.titleColor}">{{attribute.title}}</text>
    <span class="red-dot" v-if="attribute.required">*</span>
    <view class="input-content">
      <view class="input-row">
        <input @blur="validate" :maxlength="attribute.maxlength" class="input-body" v-model="CopyValue"
          :type="attribute.type" :placeholder="attribute.placeholder" />
        <view class="close-icon" v-if="attribute.clearable" @click="clearValue">
          <u-icon v-if="showClearFlag" color="#c0c4cc" name="close-circle-fill" />
        </view>
      </view>
      <view class="input-rule-text" v-if="ruleFail && !requiredFail">{{attribute.ruleText}}</view>
      <view class="input-rule-text" v-if="requiredFail">{{attribute.requiredText}}</view>
    </view>
  </view>
</template>

<script>
import { COMPREIFX } from "../../../libs/const/widget";

export default {
  name: `${COMPREIFX}text-input`,
  props: {
    attribute: Object,
    styles: Object,
  },
  data() {
    return {
      ruleFail: false,
      requiredFail: false,
      CopyValue : ''
    }
  },
  watch:{
    CopyValue(val){
      this.attribute.value = val
    }
  },
  created(){
    this.CopyValue = this.attribute.value
  },
  computed:{
    showClearFlag(){
      return !!this.CopyValue
    }
  },
  methods: {
    clearValue() {
      this.CopyValue = ''
      this.ruleFail = false
    },
    validate() {
      return new Promise((resolve) => {
        this.$nextTick(() => {
          let tips = undefined
          if (this.attribute.required) {
            this.requiredFail = !this.attribute.value
            tips = this.requiredFail ? this.attribute.requiredText : undefined
          }
          if (!tips) {
            switch (this.attribute.rule) {
              case 'email':
                this.ruleFail = (this.attribute.value && !this.$u.test.email(this.attribute.value))
                tips = this.ruleFail ? this.attribute.ruleText : undefined
                break;
              case 'mobile':
                this.ruleFail = (this.attribute.value && !this.$u.test.mobile(this.attribute.value))
                tips = this.ruleFail ? this.attribute.ruleText : undefined
                break;
            }
          }
          resolve(tips)
        })
      })
    }
  }
};
</script>

<style scoped lang="scss">
.content {
  padding: 15rpx 20rpx;
}

.title {
  color: #333;
  font-size: 28rpx;
}

.red-dot {
  color: rgb(245, 39, 39);
  margin-left: 5rpx;
}

.input-content {
  position: relative;
  margin-top: 22rpx;
}

.input-rule-text {
  color: #F05357;
  font-size: 24rpx;
  padding: 15rpx 18rpx;
}

.input-row {
  display: flex;
  border: 1rpx solid #CACACA;
}

.input-body {
  flex: 9;
  padding: 18rpx;
  border: none;
  outline: none;
  background-color: transparent;
}

.close-icon {
  flex: 1;
  display: flex;
  justify-content: center;
}
</style>
